import request from '@/utils/request'

// ==================== 学生申请管理相关API ====================

// 获取学生的申请记录
export function getStudentApplications(studentId) {
  // 添加fallback机制
  if (!studentId || studentId === 'undefined' || studentId === 'null' || studentId === '') {
    studentId = localStorage.getItem('userId') || '1'
    console.log('Fallback to localStorage userId:', studentId)
  }
  return request({
    url: '/campus/student/' + studentId + '/applications',
    method: 'get'
  })
}

// 查询申请列表
export function listApplication(query) {
  return request({
    url: '/campus/application/list',
    method: 'get',
    params: query
  })
}

// 学生提交申请
export function submitApplication(data) {
  return request({
    url: '/campus/application/submit',
    method: 'post',
    data: data
  })
}

// 新增申请
export function addApplication(data) {
  return request({
    url: '/campus/application',
    method: 'post',
    data: data
  })
}

// 修改申请
export function updateApplication(data) {
  return request({
    url: '/campus/application',
    method: 'put',
    data: data
  })
}

// 学生撤回申请
export function withdrawApplication(applicationId) {
  return request({
    url: '/campus/application/withdraw/' + applicationId,
    method: 'put'
  })
}

// 学生取消申请
export function cancelApplication(applicationId) {
  console.log('Calling cancelApplication with applicationId:', applicationId)
  return request({
    url: '/campus/application/cancel/' + applicationId,
    method: 'put'
  })
}

// 获取可用面试时段
export function getAvailableSlots(recruitmentId) {
  return request({
    url: '/campus/student/availableSlots/' + recruitmentId,
    method: 'get'
  })
}

// 预约面试
export function bookInterview(data) {
  // 调整数据格式以匹配后端期望的参数结构
  const params = {
    studentId: data.studentId,
    slotId: data.slotId,
    applicationId: data.applicationId,
    remarks: data.remarks
  };
  return request({
    url: '/campus/interviewAppointment/book',
    method: 'post',
    data: params
  })
}

// 更新面试预约
export function updateInterviewAppointment(data) {
  // 对于更新预约，使用重新安排接口
  const params = {
    appointmentId: data.appointmentId,
    newSlotId: data.slotId,
    rescheduleReason: data.remarks
  };
  return request({
    url: '/campus/interviewAppointment/reschedule',
    method: 'put',
    data: params
  })
}

// 添加默认导出以确保模块正确导入
export default {
  getStudentApplications,
  listApplication,
  submitApplication,
  addApplication,
  updateApplication,
  withdrawApplication,
  cancelApplication,
  getAvailableSlots,
  bookInterview,
  updateInterviewAppointment
}